package com.ding.common;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

//等待者
public class Waiter {

    private static Map<Runnable, Timer> map = new HashMap<>();

    public static TaskHolder setTimeout(final Runnable runnable, long time) {
        TimerTask r = new TimerTask() {
            @Override
            public void run() {

                //执行之后直接删除
                runnable.run();
                map.remove(runnable);
            }
        };
        Timer timer = new Timer();
        timer.schedule(r, time);
        map.put(runnable, timer);
        return new TaskHolder(runnable);
    }

    public static void clearTimeout(TaskHolder taskHolder) {
        taskHolder.clear();
    }

    public static void clearInterval(TaskHolder taskHolder) {
        taskHolder.clear();
    }

    public static TaskHolder setInterval(final Runnable runnable, long time) {
        TimerTask r = new TimerTask() {
            @Override
            public void run() {
                runnable.run();
            }
        };
        Timer timer = new Timer();
        timer.schedule(r, time, time);
        map.put(runnable, timer);
        return new TaskHolder(runnable);
    }


    public static class TaskHolder {
        private Runnable runnable;

        private TaskHolder(Runnable runnable) {
            this.runnable = runnable;
        }

        public void clear() {
            Timer timer = map.get(this.runnable);
            if (timer != null) {
                timer.cancel();
                map.remove(this.runnable);
            }
        }
    }

}
